#pragma once
#include "nocopy.hpp"
#include "Comm.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

#include <iostream>
#include <cstdint>
#include <cstring>
#include <cerrno>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <signal.h>
class TcpServer;
struct ThreadData   
{
    ThreadData(int sockfd, TcpServer* ptr, const struct sockaddr_in& addr)
        :_sockfd(sockfd), _ptr(ptr), _addr(addr)
    {}
    ~ThreadData()
    {
        close(_sockfd);
    }
    int _sockfd;
    TcpServer* _ptr;
    InetAddr _addr;
};
#define CONV(addr_ptr) ((struct sockaddr *)(addr_ptr))
class TcpServer : public nocopy
{
public:
    TcpServer(int port)
        : _port(port), _isinit(false)
    {
    }
    void Init()
    {
        // 1.创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg.LogMessage(Fatal, "lietensock create error, errno: %d, %s\n", errno, strerror(errno));
            exit(listensockfd_err);
        }
        lg.LogMessage(Debug, "lietensock create success\n");

        // 解决重复bind失败的问题
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof opt);

        // 2.bind
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = INADDR_ANY;
        server.sin_port = htons(_port);
        int ok = bind(_listensock, CONV(&server), sizeof server);
        if (ok == -1)
        {
            lg.LogMessage(Fatal, "bind error, errno: %d, %s\n", errno, strerror(errno));
            exit(bind_err);
        }
        lg.LogMessage(Debug, "bind success\n");

        // 3.设置fd为监听状态
        ok = listen(_listensock, 5);
        if (ok == -1)
        {
            lg.LogMessage(Fatal, "listem error, errno: %d, %s\n", errno, strerror(errno));
            exit(listen_err);
        }
        lg.LogMessage(Debug, "listen success\n");

        _isinit = true;
    }
    void Service(int sockfd)
    {
        while (true)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof buffer - 1);
            std::cout << "n:" << n << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                // write(sockfd, buffer, sizeof buffer); //
                write(sockfd, buffer, strlen(buffer));

                // std::string str = buffer;
                // write(sockfd, str.c_str(), str.size());
            }
            else if (n == 0)
            {
                lg.LogMessage(Info, "client 断开连接或者读完\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
                break;
            }
        }
    }
    void Service(int sockfd, const std::string& addr)
    {
        while (true)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof buffer - 1);
            std::cout << "n:" << n << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                // write(sockfd, buffer, sizeof buffer); //
                // write(sockfd, buffer, strlen(buffer));

                std::string str = addr;
                std::cout << "TSVR " << addr << addr.size()<< std::endl; //Debug
                str += buffer;
                std::cout << "str " << str << str.size()<< std::endl; //Debug

                write(sockfd, str.c_str(), str.size());
            }
            else if (n == 0)
            {
                lg.LogMessage(Info, "client 断开连接或者读完\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
                break;
            }
        }
    }
    static void* ThreadRountine(void* args)
    {
        ThreadData* data = static_cast<ThreadData*>(args);
        pthread_detach(pthread_self());
        data->_ptr->Service(data->_sockfd, data->_addr.PrintDebug());

        delete data;
        return nullptr;
    }
    void Start()
    {
        while (_isinit)
        {
            struct sockaddr_in client;
            socklen_t len = 0;
            // std::cout << "111" << std::endl; //Debug
            int sockfd = accept(_listensock, CONV(&client), &len); // 这里失败是很正常
            std::cout << "sockfd: " << sockfd << std::endl;
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "acceept falied, errno: %d, %s\n", errno, strerror(errno));
                continue; // 三次握手失败，
            }
            lg.LogMessage(Debug, "acceept success\n");

            // v1 单进程
            //  Service(sockfd);
            //  close(sockfd);

            // v2 孙子进程跑服务
            // pid_t id = fork();
            // if (id < 0)
            // {
            //     close(sockfd);
            //     lg.LogMessage(Warning, "fork error\n");
            // }
            // else if (id == 0)
            // {
            //     if (fork() > 0)
            //         exit(0); //退出掉
            //     close(_listensock);
            //     Service(sockfd);
            //     close(sockfd);
            //     //
            // }
            // else
            // {
            //     waitpid(id, nullptr, 0);
            //     close(sockfd);
            // }

            // v3 让父进程忽略子进程的退出信号
            // signal(SIGCHLD, SIG_IGN); //父进程忽略子进程的退出信号
            // pid_t id = fork();
            // if (id < 0)
            // {
            //     close(sockfd);
            //     lg.LogMessage(Warning, "fork error\n");
            // }
            // else if (id == 0)
            // {
            //     close(_listensock);
            //     Service(sockfd);
            //     close(sockfd);
            //     exit(0);         //记得退出，不然子进程跑accept一直报错
            // }
            // else
            // {
            //     close(sockfd);
            // }

            //v4 多线程
            ThreadData* td = new ThreadData(sockfd, this, client);
            pthread_t tid;
            pthread_create(&tid, nullptr, ThreadRountine, td);
        }
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isinit;
};